package com.winkyle.woodenfish.widget;

import android.content.Context;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;

/**
 * @author winkyle
 * @date 2018/06/15
 * @description 继承自 {@link LinearLayout}的底部工具条类
 */

public class BottomBar extends LinearLayout {
    private static final int TRANSLATE_DURATION_MILLIS = 200;

    private final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    private boolean visible = true;

    private LinearLayout tabLayout;
    private LayoutParams tabParams;
    private int currentPosition = 0;
    private OnTabSelectedListener listener;

    /**
     * @param context 上下文
     */
    public BottomBar(Context context) {
        this(context, null);
    }

    /**
     * @param context 上下文
     * @param attrs 组件的参数资源
     */
    public BottomBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * @param context 上下文
     * @param attrs 组件的参数资源
     * @param defStyleAttr 样式
     */
    public BottomBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * @description 初始化工具条布局，背景白色，水平布局，将tabLayout加进工具条，设置tabLayout中的tab项参数。
     * @param context 上下文
     * @param attrs 组件的参数资源
     */
    private void init(Context context, AttributeSet attrs) {
        //无关紧要，这是对tabLayout的
        setOrientation(HORIZONTAL);

        tabLayout = new LinearLayout(context);
        tabLayout.setBackgroundColor(Color.WHITE);
        tabLayout.setOrientation(LinearLayout.HORIZONTAL);
        addView(tabLayout, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        tabParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        tabParams.weight = 1;
    }

    /**
     * @description 为tab项设置监听，并将tab项加进tabLayout中
     * @param tab 被添加进的tab项
     * @return
     */
    public BottomBar addItem(final BottomBarTab tab) {
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener == null) return;

                int pos = tab.getTabPosition();
                if (currentPosition == pos) {
                    listener.onTabReselected(pos);
                } else {
                    listener.onTabSelected(pos, currentPosition);
                    tab.setSelected(true);
                    listener.onTabUnselected(currentPosition);
                    tabLayout.getChildAt(currentPosition).setSelected(false);
                    currentPosition = pos;
                }
            }
        });
        tab.setTabPosition(tabLayout.getChildCount());
        tab.setLayoutParams(tabParams);
        tabLayout.addView(tab);
        return this;
    }

    /**
     * @description 设置tab项监听
     * @param onTabSelectedListener
     */
    public void setOnTabSelectedListener(OnTabSelectedListener onTabSelectedListener) {
        listener = onTabSelectedListener;
    }

    /**
     * @description 设置当前tab项
     * @param position 设置的tab项地址
     */
    public void setCurrentItem(final int position) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.getChildAt(position).performClick();
            }
        });
    }

    /**
     * @description tab项监听
     */
    public interface OnTabSelectedListener {
        /**
         * @description tab项被选中
         * @param position 当前被选中的tab项地址
         * @param prePosition 上一个被选中的tab项地址
         */
        void onTabSelected(int position, int prePosition);

        /**
         * @description tab项未被选中
         * @param position 未被选中的tab项地址
         */
        void onTabUnselected(int position);

        /**
         * @description tab项被重复选中
         * @param position 被选中的tab项地址
         */
        void onTabReselected(int position);
    }

    public int getCurrentItemPosition() {
        return currentPosition;
    }

    /**
     * @description 隐藏
     */
    public void hide() {
        hide(true);
    }

    /**
     * @description 显示
     */
    public void show() {
        show(true);
    }

    /**
     * @description 是否带动画的隐藏
     * @param anim 是否带动画
     */
    public void hide(boolean anim) {
        toggle(false, anim, false);
    }

    /**
     * @description 是否带动画的显示
     * @param anim 是否带动画
     */
    public void show(boolean anim) {
        toggle(true, anim, false);
    }

    /**
     * @description 是否显示
     * @return
     */
    public boolean isVisible() {
        return visible;
    }

    /**
     * @description 隐藏显示的切换
     * @param visible 隐藏或显示
     * @param animate 是否带动画
     * @param force
     */
    private void toggle(final boolean visible, final boolean animate, boolean force) {
        if (visible != visible || force) {
            this.visible = visible;
            int height = getHeight();
            if (height == 0 && !force) {
                ViewTreeObserver vto = getViewTreeObserver();
                if (vto.isAlive()) {
                    // view树完成测量并且分配空间而绘制过程还没有开始的时候播放动画。
                    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        @Override
                        public boolean onPreDraw() {
                            ViewTreeObserver currentVto = getViewTreeObserver();
                            if (currentVto.isAlive()) {
                                currentVto.removeOnPreDrawListener(this);
                            }
                            toggle(visible, animate, true);
                            return true;
                        }
                    });
                    return;
                }
            }
            int translationY = visible ? 0 : height;
            if (animate) {
                animate().setInterpolator(interpolator)
                        .setDuration(TRANSLATE_DURATION_MILLIS)
                        .translationY(translationY);
            } else {
                ViewCompat.setTranslationY(this, translationY);
            }
        }
    }

    /**
     * @description 保存状态
     * @return
     */
    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        return new SavedState(superState, currentPosition);
    }

    /**
     * @description 恢复状态
     * @param state
     */
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        if (currentPosition != ss.position) {
            tabLayout.getChildAt(currentPosition).setSelected(false);
            tabLayout.getChildAt(ss.position).setSelected(true);
        }
        currentPosition = ss.position;
    }

    /**
     * @description 保存的状态数据的类
     */
    static class SavedState extends BaseSavedState {
        private int position;

        public SavedState(Parcel source) {
            super(source);
            position = source.readInt();
        }

        public SavedState(Parcelable superState, int position) {
            super(superState);
            this.position = position;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(position);
        }

        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}
